package com.cloud.feeling.ststem.service.impl;

import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.cloud.common.CommonConstants;
import com.cloud.common.RestCode;
import com.cloud.common.RestResponse;
import com.cloud.common.model.User;
import com.cloud.common.model.UserToken;
import com.cloud.common.utils.PageQuery;
import com.cloud.common.utils.RequestHolder;
import com.cloud.feeling.ststem.common.UserException;
import com.cloud.feeling.ststem.common.UserException.Type;
import com.cloud.feeling.ststem.mapper.UserMapper;
import com.cloud.feeling.ststem.service.UserService;
import com.cloud.feeling.ststem.utils.HashUtils;
import com.cloud.feeling.ststem.utils.JwtHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.ImmutableMap;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private StringRedisTemplate redisTemplate;
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public UserToken auth(User user) {
		if (StringUtils.isBlank(user.getUserName()) || StringUtils.isBlank(user.getPassWord())) {
	      throw new UserException(Type.USER_AUTH_FAIL,"认证失败");
	    }
		user.setPassWord(HashUtils.encryPassword(user.getPassWord()));
		List<User> select = userMapper.select(user);
		user.setId(select.get(0).getId());
		user.setPassWord(HashUtils.encryPassword(user.getPassWord()));
		String token =  JwtHelper.genToken(ImmutableMap.of("id", user.getId().toString(), "username", user.getUserName(),"password",user.getPassWord(),"ts",Instant.now().getEpochSecond()+""));
		redisTemplate.opsForValue().set(user.getId().toString(), token);
	    redisTemplate.expire(user.getId().toString(), 30, TimeUnit.MINUTES);//设置redis超时时间
	    
	    UserToken userToken=new UserToken();
	    userToken.setUserId(user.getId());
	    userToken.setUserName(user.getUserName());
	    userToken.setToken(token);
		return userToken;
	}

	@Override
	public User getUserByToken(String token) {
		Map<String, String> map = null;
	    try {
	      map = JwtHelper.verifyToken(token);
	    } catch (Exception e) {
	      return null;
	    }
	    String id =  map.get("id");
	    Long expired = redisTemplate.getExpire(id);
	    if (expired > 0L) {
	    	redisTemplate.opsForValue().set(id, token);//更新登录时间
	        redisTemplate.expire(id, 30, TimeUnit.MINUTES);
	        User user=new User();
	        user.setId(Long.valueOf(id));
	        user.setUserName(map.get("username"));
	        user.setPassWord(map.get("password"));
	        return user;
	    }
	    return null;
	}

	@Override
	public UserToken logout(String token) {
		if(token==null && StringUtils.isNoneBlank(token)){
			token=RequestHolder.getRequest().getHeader(CommonConstants.TOKEN_COOKIE);
		}
		Map<String, String> map = null;
	    try {
	      map = JwtHelper.verifyToken(token);
	    } catch (Exception e) {
	      throw new UserException(Type.USER_NOT_LOGIN,"用户未登录");
	    }
	    String id = map.get("id");//删除redis中key
	    redisTemplate.delete(id);
	    UserToken usertoken=new UserToken();
	    usertoken.setUserId(Long.valueOf(id));
		return usertoken;
	}

	@Override
	public void saveUser(User user) {
		user.setPassWord(HashUtils.encryPassword(user.getPassWord() ==null ? "123456" : user.getPassWord()));
		if(user!=null&&user.getId()!=null) {
			userMapper.updateUser(user);
		}else {
			userMapper.saveUser(user);
		}
	}

	@Override
	public PageInfo<User> list(PageQuery params) {
		PageHelper.startPage(params);
		PageInfo<User> userinfo=new PageInfo<User>(userMapper.selectlist());
		return userinfo;
	}

	@Override
	public RestResponse<RestCode> verificationUsername(User user) {
		List<User> userlist =null;
		if(StringUtils.isEmpty(user.getId()+"")) {
			userlist = userMapper.select(user);
		}else {
			userlist = userMapper.selectUsername(user);
		}
		if(userlist!=null&&userlist.size()>0) {
			return RestResponse.error(RestCode.REPEATUSERAME);
		}
		return RestResponse.success();
	}

	@Override
	public User select(User user) {
		return userMapper.select(user).get(0);
	}

	@Override
	public RestResponse<RestCode> deleteUser(Integer[] ids) {
		userMapper.deleteUser(ids);
		return RestResponse.success();
	}
	
}
